<?php
/**
 * Modelo da classe Content
 * @filesource
 * @author       Mateus Reis Martins
 * @subpackage   user.app.models
 * @version      1.1
 */

class Nadeb_Model extends Zend_Db_Table
{

	protected $_name      = "";
	protected $_primary   = "";
	protected $_activeCol = "";
	protected $response   = "";
	
	public function init()
	{
		
	}
	
	public function swap_active($_id)
	{
		$rows  = $this->find($_id)->toArray();
		$total = $rows[0][$this->_activeCol];
			
		if( !$total )
			$value = "1";
		else
			$value = "0";
			
			
		if($this->update( 
			array( $this->_activeCol => $value),
			$this->getAdapter()->quoteInto($this->_primary[1].'= ?', $_id)) 
		)
			$this->response = "Dados atualizados com sucesso!";
		else
			$this->response = "Erro ao atualizar dados!";
	}
	
	public function list_galery_json($_folder)
	{
		$folder = "/public/uploads/" . $_folder . "/";
		$files  = new Nadeb_Folder();
		$lista  = $files->listFiles( $folder );
		$file   = $_SERVER["DOCUMENT_ROOT"] . $folder . "info.inf";
		
		if(!is_file( $file ) && is_dir( $_SERVER["DOCUMENT_ROOT"] . $folder ))
		{
			foreach($lista as $key => $value)
			{
				$vars[$key]["file"]    = $value;
				$vars[$key]["legenda"] = "";
			}
			
			$json = Zend_Json::encode($vars);
			Nadeb_Savefile::save($file,$json,true);
			return $json;
		}
		elseif(is_file( $file ))
		{
			return Nadeb_Savefile::get($file);
		}
		
		return false;
	}
	
	public function add_to_folder($_folder)
	{
		$patch = "/public/uploads/" . $_folder . "/";
		
		$add = new Nadeb_File_UploadFiles();
		$new_file = $add->save_file($_FILES["addfiles"], $patch);
		
		@mkdir($_SERVER["DOCUMENT_ROOT"] . $patch . '/temp/', 0777,true);
		@chmod($_SERVER["DOCUMENT_ROOT"] . $patch . '/temp/', 0777,true);
		
    	$image = new Nadeb_CropImages();
    	$image->set_patch( $patch )
    	      ->set_file( $new_file )
    	      ->set_newName(  "temp/nadeb-temp-{$new_file}" )
    	      ->set_newSize('100','100')
    	      ->create()
    	      ->auto_crop()
    	      ->make_file();
		
		$file = $_SERVER["DOCUMENT_ROOT"] . "/public/uploads/" . $_folder . "/info.inf";
		$old_file = Nadeb_Savefile::get($file);
		
		$vars   = Zend_Json::decode($old_file);
		$ultimo = count($vars);
		$vars[$ultimo]["file"]    = $new_file;
		$vars[$ultimo]["legenda"] = "";
		
		$json = Zend_Json::encode($vars);
		Nadeb_Savefile::save($file,$json,true);
		
		return "Arquivos enviados com sucesso!";
	}
	
	public function del_to_folder($_params)
	{
		$file = $_SERVER["DOCUMENT_ROOT"] . "/public/uploads/" . $_params["folder"] . "/" . $_params["file"] . "." . $_params["ext"];
		unlink( $file );
		
		$file = $_SERVER["DOCUMENT_ROOT"] . "/public/uploads/" . $_params["folder"] . "/temp/nadeb-temp-" . $_params["file"] . "." . $_params["ext"];
		unlink( $file );
		
		return "Arquivo excluido com sucesso";
	}
	
	public function save_galery_json($_folder)
	{
		$file  = $_SERVER["DOCUMENT_ROOT"] . "/public/uploads/" . $_folder . "/info.inf";
		foreach($_POST["file"] as $key => $value)
		{
			$vars[$key]["file"]    = $value;
			$vars[$key]["legenda"] = $_POST["legenda"][$key];
		}
		
		$json = Zend_Json::encode($vars);
		Nadeb_Savefile::save($file,$json,true);
		
		return "Legendas salvas com sucesso";
	}
	
	public function save_order($_neworder)
	{
		$db = Zend_Registry::get("db");
		$array = explode(",",$_neworder);
		for($i=1; $i < count($array); $i++)
		{
			$db->query( "UPDATE {$this->_name} SET ".substr($this->_primary,0,4)."order = {$i} WHERE {$this->_primary} = {$array[$i]}" );
		}
		
		return "Ordem atualizada com sucesso...";
	}
	
	public function createMVC($_param)
	{
		@mkdir($_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/views/scripts/" . $this->padronizedNames($_param['name']), 0777, true);
		
		$_file[] = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/Controllers/" . ucfirst($_param['name']) . "Controller.php";
		$_txt[]  = "<?php\nclass " . ucfirst($_param['name']) . "Controller extends Nadeb_Controller_Front\n{\n\tpublic function indexAction()\n\t{\n\t\t\n\t}\n}\n";
		
		$_file[] = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/Models/" . ucfirst($_param['name']) . ".php";
		$_txt[]  = "<?php\n/**\n * Modelo da classe " . ucfirst($_param['name']) . "\n * @filesource\n * @author       Mateus Reis Martins\n * @subpackage   user.app.models\n * @version      1.1\n */\n\nclass Default_Models_" . ucfirst($_param['name']) . " extends Zend_Db_Table_Abstract\n{\n\tprotected \$_name      = \"" . $_param['name'] . "\";\n\tprotected \$_primary   = \"" . substr(0,3,$_param['name']) . "_id\";\n\tprotected \$result;\n\n\tpublic function get_result()\n\t{\n\t\treturn \$this->result;\n\t\t}\n\n}";
		
		$_file[] = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/views/scripts/" . $this->padronizedNames($_param['name']) . "/index.phtml";
		$_txt[]  = "";

		for($i=0;$i < count($_file);$i++)
		{
			if( !is_file( $_file[$i] ) )
			{
				$fp = fopen($_file[$i],'w');
				fwrite($fp, $_txt[$i]);
				fclose($fp);
				
				$this->response = "controle criado porra!";
			}
			else
			{
				$this->response = "este controle ja existe";
			}
		}
		
		
	}
	
	public function createAction($_param)
	{
		$_file = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/Controllers/" . ucfirst($_param['name']) . "Controller.php";
	 	$fo = fopen($_file, "r");
	 	$body = fread($fo, filesize($_file));
		
		$body = substr($body,0,strrpos($body,"}"));
		$body = substr($body,0,strrpos($body,"}"));
		$body .= "}\n\n\tpublic function " . $_param['act'] . "Action()\n\t{\n\t\t\n\t}\n}\n";
		
		$fp = fopen($_file,'w');
		fwrite($fp, $body);
		fclose($fp);
		
		$_file = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/views/scripts/" . $this->padronizedNames($_param['name']) . "/" . $this->padronizedNames($_param['act']) . ".phtml";
		$_txt  = "";
		
		$fp = fopen($_file,'w');
		fwrite($fp, $_txt);
		fclose($fp);
		
		$this->response = "enfiamos a ação dentro do controlle";
	}
	
	public function deleteMVC($_param)
	{
		$_file[] = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/Controllers/" . ucfirst($_param['name']) . "Controller.php";
		$_txt[]  = "<?php\nclass " . ucfirst($_param['name']) . "Controller extends Nadeb_Controller_Front\n{\n\tpublic function indexAction()\n\t{\n\t\t\n\t}\n}\n";
		
		$_file[] = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/Models/" . ucfirst($_param['name']) . ".php";
		$_txt[]  = "<?php\n/**\n * Modelo da classe " . ucfirst($_param['name']) . "\n * @filesource\n * @author       Mateus Reis Martins\n * @subpackage   user.app.models\n * @version      1.1\n */\n\nclass Default_Models_" . ucfirst($_param['name']) . " extends Zend_Db_Table_Abstract\n{\n\tprotected \$_name      = \"" . $_param['name'] . "\";\n\tprotected \$_primary   = \"" . substr(0,3,$_param['name']) . "_id\";\n\tprotected \$result;\n\n\tpublic function get_result()\n\t{\n\t\treturn \$this->result;\n\t\t}\n\n}";
		
		for($i=0;$i < count($_file);$i++)
		{
			@unlink( $_file[$i] );
		}
		
		$folder = $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/views/scripts/" . $_param['name'] . "/";
    	$dir    = dir($folder);
		$dir->rewind();
		
		while($files=$dir->read())
		{
			if ($files != "." && $files != "..")
			{
				@unlink( $folder . $files );
			}
		}
		@rmdir( $_SERVER["DOCUMENT_ROOT"] . "/application/modules/" . ucfirst($_param['module']) . "/views/scripts/" . $_param['name'] );
				
		$this->response = "apagamo a porra toda";
	}
	
	private function padronizedNames($_string)
	{
		$arrayTest = "WERTYUIOPASDFGHJKLZXCVBNM";
		
		for($i = 0; $i < strlen($arrayTest); $i++ )
		{
			if( strpos($_string, $arrayTest[$i],1) )
			{
				$str = str_replace($arrayTest[$i],'-' . $arrayTest[$i],$_string);
				
				return strToLower($str);
				
			}
		}
			
		return $_string;
	}
	
	public static function activeValues()
	{
		return array("0" => "Não", "1" => "Sim");
	}
	
	public function get_result()
	{
		return $this->response;
	}
	
}